package com.software.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.software.bean.*;
import com.software.dto.*;
import com.software.mapper.*;
import com.software.service.OrderService;
import com.software.utils.AssertUtil;
import com.software.vo.OrderVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wyj
 * @since 2024-04-04
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderBean> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CustomerAddressMapper customerAddressMapper;

    @Autowired
    private CartMapper cartMapper;

    /**
     * @description:初步生成未支付订单---postOrder方法
     * @author: wyj
     * @date: 2024/4/4 20:17
     * @param:
     * @return:
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Integer> addOrder(AddOrderDto addOrderDto) {
        //参数校验
        AssertUtil.isTrue(addOrderDto.getBuyerId() == null, "用户id不能为空");
        AssertUtil.isTrue(addOrderDto.getProductId().size() == 0, "商品id不能为空");
        //校验参数是否合法

        CustomerInfoBean customerInfoBean = customerInfoMapper.selectById(addOrderDto.getBuyerId());
        AssertUtil.isTrue(customerInfoBean == null, "用户不存在");
        List<ProductBean> productBeans = productMapper.selectBatchIds(addOrderDto.getProductId());
        AssertUtil.isTrue(productBeans.size() == 0, "商品不存在");
        // 判断商品状态
        for (ProductBean productBean : productBeans) {
            AssertUtil.isTrue(productBean.getProductStatus() != 1, "商品已经失效了");
        }
        // 修改订单状态
        for (ProductBean productBean : productBeans) {
            // 修改状态
            productBean.setProductStatus(2);
            // 取消在主页展示
            productBean.setIsHome(0);
            int i = productMapper.updateById(productBean);
            AssertUtil.isTrue(i != 1, "修改产品表状态失败");
        }
        List<Integer> resultList = new ArrayList<>();
        for (int i = 0; i < addOrderDto.getProductId().size(); i++) {
            OrderBean orderBean = new OrderBean();
            orderBean.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
            //  1 待支付
            orderBean.setStatus(1);
            orderBean.setCreateTime(new Date());
            orderBean.setBuyerId(addOrderDto.getBuyerId());
            orderBean.setProductId(addOrderDto.getProductId().get(i));
            orderBean.setSellerId(productBeans.get(i).getCustomerId());
            int insert = orderMapper.insert(orderBean);
            AssertUtil.isTrue(insert != 1, "添加失败");

            OrderBean result = orderMapper.selectById(orderBean.getId());
            resultList.add(result.getId());
        }

        AssertUtil.isTrue(resultList.size() == 0, "添加失败");
        return resultList;
    }

    /**
     * @description:查用户的所有交易订单
     * @author: wyj
     * @date: 2024/4/4 20:17
     * @param:
     * @return:
     */
    @Override
    public List<OrderBean> getOrderList(Integer customerId) {
        //参数校验
        AssertUtil.isTrue(customerId == null, "参数异常");
        //校验参数是否合法
        CustomerInfoBean customerInfoBean = customerInfoMapper.selectById(customerId);
        AssertUtil.isTrue(customerInfoBean == null, "用户不存在");
        List<OrderBean> orderBeans = orderMapper.getOrderListByBuyerId(customerId);
        return orderBeans;
    }

    /**
     * @description:查所有卖出的商品
     * @author: wyj
     * @date: 2024/4/5 0:08
     * @param:
     * @return:
     */
    @Override
    public List<OrderBean> getProductForDeliveryList(Integer customerId) {
        //参数校验
        AssertUtil.isTrue(customerId == null, "参数异常");
        CustomerInfoBean customerInfoBean = customerInfoMapper.selectById(customerId);
        AssertUtil.isTrue(customerInfoBean == null, "返回值异常");
        List<OrderBean> productForDeliveryList = orderMapper.getProductForDeliveryList(customerId);
        return productForDeliveryList;
    }

    /**
     * @description:添加快递单号
     * @author: wyj
     * @date: 2024/4/5 1:19
     * @param:
     * @return:
     */
    @Override
    public Integer addDelivery(AddDeliveryNoDto addDeliveryNoDto) {
        //参数校验
        AssertUtil.isTrue(addDeliveryNoDto.getCid() == null, "参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(addDeliveryNoDto.getDeliveryNo()), "参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(addDeliveryNoDto.getOrderNo()), "参数异常");
        AssertUtil.isTrue(addDeliveryNoDto.getPid() == null, "参数异常");
        //校验参数合法性
        CustomerInfoBean customerInfoBean = customerInfoMapper.selectById(addDeliveryNoDto.getCid());
        AssertUtil.isTrue(customerInfoBean == null, "用户不存在");
        ProductBean productBean = productMapper.selectById(addDeliveryNoDto.getPid());
        AssertUtil.isTrue(productBean == null, "商品不存在");
        OrderBean orderBean = orderMapper.selectByOrderNo(addDeliveryNoDto.getOrderNo());
        AssertUtil.isTrue(orderBean == null, "订单不存在");

        productBean.setProductStatus(3);
        int i1 = productMapper.updateById(productBean);
        AssertUtil.isTrue(i1 != 1, "修改失败");
        orderBean.setDeliveryNo(addDeliveryNoDto.getDeliveryNo());
        orderBean.setStatus(3);
        orderBean.setSendTime(new Date());
        int i = orderMapper.updateById(orderBean);
        return i == 1 ? 1 : 0;
    }

    /**
     * @description:分页查询订单列表
     * @author: wyj
     * @date: 2024/4/5 10:10
     * @param:
     * @return:
     */
    @Override
    public IPage<OrderBean> getOrderListForPage(Integer pageNum, Integer pageSize) {
        Page<OrderBean> page = new Page<>(pageNum, pageSize);
        IPage<OrderBean> orderListForPage = orderMapper.getOrderListForPage(page);
        return orderListForPage;
    }

    /**
     * @description:支付页面的订单信息展示
     * @author: wyj
     * @date: 2024/4/5 11:33
     * @param:
     * @return:
     */
    @Override
    public OrderVo getOrderInfoByOrderId(OrderInfoByOrderIdsDto orderInfoByOrderIdsDto) {
        System.out.println(orderInfoByOrderIdsDto);

        //参数校验
        AssertUtil.isTrue(orderInfoByOrderIdsDto.getOrderIdArray().size() == 0, "订单信息异常");
        AssertUtil.isTrue(orderInfoByOrderIdsDto.getCid() == null, "用户信息异常");
        //校验参数合法性
        CustomerInfoBean customerInfoBean = customerInfoMapper.selectById(orderInfoByOrderIdsDto.getCid());
        AssertUtil.isTrue(customerInfoBean == null, "用户不存在");
        List<OrderBean> orderBeans = orderMapper.selectByIds(orderInfoByOrderIdsDto.getOrderIdArray());
        AssertUtil.isTrue(orderBeans.size() == 0, "订单不存在");
        AssertUtil.isTrue(orderBeans.size() != orderInfoByOrderIdsDto.getOrderIdArray().size(), "订单信息异常");
        // 查用户默认地址
        CustomerAddressBean customerAddressBean = customerAddressMapper.getIsDefaultAddress(orderInfoByOrderIdsDto.getCid());
        OrderVo orderVo = new OrderVo();
        orderVo.setCustomerAddressBean(customerAddressBean);
        orderVo.setOrderBeans(orderBeans);
        return orderVo;
    }

    /**
     * @description:支付订单
     * @author: wyj
     * @date: 2024/4/5 12:28
     * @param:
     * @return:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer postOrderToPay(OrderPayDto orderPayDto) {
        AssertUtil.isTrue(orderPayDto.getOrderIdArray().size() == 0, "订单id异常");
        AssertUtil.isTrue(orderPayDto.getCid() == null, "参数异常");
        AssertUtil.isTrue(orderPayDto.getAid() == null, "参数异常");
        CustomerInfoBean customerInfoBean = customerInfoMapper.selectById(orderPayDto.getCid());
        AssertUtil.isTrue(customerInfoBean == null, "用户不存在");
        CustomerAddressBean customerAddressBean = customerAddressMapper.selectById(orderPayDto.getAid());
        AssertUtil.isTrue(customerAddressBean == null, "地址不存在");
        List<OrderBean> orderBeans = orderMapper.selectByIds(orderPayDto.getOrderIdArray());
        AssertUtil.isTrue(orderBeans == null, "订单不存在");
        AssertUtil.isTrue(orderBeans.size() != orderPayDto.getOrderIdArray().size(), "订单信息异常");

        // pid 用于删除购物车里的商品信息
        List<Integer> pid = new ArrayList<>();
        for (OrderBean orderBean : orderBeans) {
            orderBean.setStatus(2);
            if (StringUtils.isEmpty(orderPayDto.getOrderDesc())) {
                orderPayDto.setOrderDesc("无");
            }else{
                orderPayDto.setOrderDesc(orderPayDto.getOrderDesc());
            }
            ProductBean productBean = productMapper.selectById(orderBean.getProductId());
            orderBean.setOrderDesc(orderPayDto.getOrderDesc());
            orderBean.setOrderPrice(productBean.getProductPrice());
            orderBean.setAddressId(orderPayDto.getAid());
            orderBean.setPayTime(new Date());
            pid.add(orderBean.getProductId());
            int i = orderMapper.updateById(orderBean);
            AssertUtil.isTrue(i != 1, "支付失败");

        }
        // 判断商品是否再购物车里
        List<CartBean> cartBeanList = cartMapper.selectByPidAndCid(pid, orderPayDto.getCid());
        if (cartBeanList.size() != 0) {
            List<Integer> cartId = new ArrayList<>();
            for (CartBean cartBean : cartBeanList) {
                cartId.add(cartBean.getId());
            }
            int i = cartMapper.deleteBatchIds(cartId);
            AssertUtil.isTrue(i != cartId.size(), "购物车异常");
        }

        return 1;
    }

    /**
     * @description:查订单详情用于订单详情页面
     * @author: wyj
     * @date: 2024/4/5 13:47
     * @param:
     * @return:
     */
    @Override
    public OrderBean getOrderDetailByOid(Integer oid) {
        AssertUtil.isTrue(oid == null, "参数异常");
        OrderBean orderBean = orderMapper.getOrderDetailByOid(oid);
        AssertUtil.isTrue(orderBean == null, "订单不存在");
        return orderBean;

    }

    /**
     * @description:退款功能实现
     * @author: wyj
     * @date: 2024/4/5 14:56
     * @param:
     * @return:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer putOrderToRefund(Integer oid) {
        //参数校验
        AssertUtil.isTrue(oid == null, "参数异常");
        OrderBean orderBean = orderMapper.selectById(oid);
        AssertUtil.isTrue(orderBean == null, "订单不存在");
        //修改订单状态
        orderBean.setCloseTime(new Date());
        // 设置订单状态为取消
        orderBean.setStatus(5);
        orderBean.setEndTime(new Date());
        int result = orderMapper.updateById(orderBean);
        AssertUtil.isTrue(result != 1, "修改失败");
        // 修改产品表状态
        ProductBean productBean = productMapper.selectById(orderBean.getProductId());
        productBean.setProductStatus(1);
        // 重新显示到主页上
        productBean.setIsHome(1);
        int i = productMapper.updateById(productBean);
        AssertUtil.isTrue(i != 1, "修改失败");
        return i == 1 ? 1 : 0;
    }

    /**
     * @description:收货功能实现
     * @author: wyj
     * @date: 2024/4/5 15:52
     * @param:
     * @return:
     */
    @Override
    public Integer putOrderToReceive(Integer oid) {
        AssertUtil.isTrue(oid == null, "参数异常");
        OrderBean orderBean = orderMapper.getOrderDetailByOid(oid);
        AssertUtil.isTrue(orderBean == null, "订单不存在");
        orderBean.setStatus(4);
        orderBean.setEndTime(new Date());
        orderBean.setCloseTime(new Date());
        int update = orderMapper.updateById(orderBean);
        AssertUtil.isTrue(update != 1, "修改失败");
        ProductBean productBean = productMapper.selectById(orderBean.getProductId());
        //修改产品表状态
        productBean.setProductStatus(4);
        int i = productMapper.updateById(productBean);
        return i == 1 ? 1 : 0;
    }

    /**
     * @description:后台点击详情按钮获取订单详细信息
     * @author: wyj
     * @date: 2024/4/5 21:09
     * @param:
     * @return:
     */
    @Override
    public OrderBean getOrderDetail(Integer oid) {
        AssertUtil.isTrue(oid == null, "参数异常");
        OrderBean orderBean = orderMapper.getOrderDetailByOid(oid);
        AssertUtil.isTrue(orderBean == null, "订单不存在");
        return orderBean;

    }

    /**
     * @description:饼图
     * @author: wyj
     * @date: 2024/4/9 17:23
     * @param:
     * @return:
     */
    @Override
    public List<Map<String, Object>> orderCharts() {
        Map<String, Object> mapList = orderMapper.orderCharts();
        List<Map<String, Object>> maps = new ArrayList<>();
        //重新封装返回的结果集
        mapList.forEach((k, v) -> {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("name", k);
            map1.put("value", v);
            maps.add(map1);
        });
        return maps;
    }

    /**
     * @description:卖家取消订单
     * @author: wyj
     * @date: 2024/4/9 17:28
     * @param:
     * @return:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer cancelOrder(Integer oid) {
        // 校验参数
        AssertUtil.isTrue(oid == null, "参数异常");
        OrderBean orderBean = orderMapper.selectById(oid);
        // 设置5 为取消订单
        orderBean.setStatus(5);
        //设置关闭时间
        orderBean.setCloseTime(new Date());
        orderBean.setEndTime(new Date());
        AssertUtil.isTrue(orderBean == null, "订单不存在");
        //修改订单状态重新上架
        Integer productId = orderBean.getProductId();
        ProductBean productBean = productMapper.selectById(productId);
        productBean.setProductStatus(1);
        productBean.setIsHome(1);
        int update = productMapper.updateById(productBean);
        AssertUtil.isTrue(update != 1, "修改失败");
        int i = orderMapper.updateById(orderBean);
        return i == 1 ? 1 : 0;
    }

    /**
     * @description:卖家取消付款
     * @author: wyj
     * @date: 2024/4/10 22:45
     * @param:
     * @return:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer cancelPay(CancelOrderPayDto cancelOrderPayDto) {
        //校验参数
        AssertUtil.isTrue(cancelOrderPayDto.getOrderIdArray().size() == 0, "订单id能为空");
        AssertUtil.isTrue(cancelOrderPayDto.getCid() == null, "用户信息不能为空");
        CustomerInfoBean customerInfoBean = customerInfoMapper.selectById(cancelOrderPayDto.getCid());
        AssertUtil.isTrue(customerInfoBean == null, "用户不存在");
        //修改订单状态
        List<OrderBean> orderBeans = orderMapper.selectByIds(cancelOrderPayDto.getOrderIdArray());
        orderBeans.forEach(orderBean -> {
            orderBean.setStatus(5);
            orderBean.setCloseTime(new Date());
            orderBean.setEndTime(new Date());
            int update = orderMapper.updateById(orderBean);
            AssertUtil.isTrue(update != 1, "修改失败");
        });

        // 修改产品表状态
        orderBeans.forEach(orderBean -> {
            ProductBean productBean = productMapper.selectById(orderBean.getProductId());
            productBean.setProductStatus(1);
            productBean.setIsHome(1);
            int i = productMapper.updateById(productBean);
            AssertUtil.isTrue(i != 1, "修改失败");
        });
        return 1;
    }


}
